package com.burgeon.backend.service.Impl;

import com.burgeon.backend.Rest.Tool.ISUsable;
import com.burgeon.backend.entity.Account;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.BackendService;
import com.burgeon.backend.service.ex.GetUserDataException;
import com.burgeon.backend.service.ex.InsertException;
import com.burgeon.backend.service.ex.PasswordNotMatchException;
import com.burgeon.backend.service.ex.UserNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class BackendServiceImpl implements BackendService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public String BosOrXe(String account) {
        return accountMapper.GetAccData(account).getSystem();
    }

    @Override
    public Account Login(String account, String password) throws UserNotFoundException, PasswordNotMatchException {
        Account data = accountMapper.login(account);
        if (data == null) {
            throw new UserNotFoundException("用户不存在");
        }
        if (!password.equals(data.getPassword())) {
            throw new PasswordNotMatchException("密码输入错误");
        }

        return data;
    }

    @Override
    public Info InsertInfo(Info info, String account) throws InsertException {

        ISUsable isUsable = new ISUsable(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            if (!"0".equals(isUsable.getData())){
                throw new InsertException("连接失败");
            }
        } catch (Exception e) {

            throw new InsertException("连接失败");
        }

        String infoId = accountMapper.GetInfoidForAccount(account);
        info.setId(infoId);


        try {
            Integer row = accountMapper.InsertInfoData(info);
            if (row != 1) {
                accountMapper.UpdataInfoData(info);
            }else {
                throw new InsertException("数据错误");
            }
        }catch (Exception e){
             accountMapper.UpdataInfoData(info);
        }

        return info;
    }

    @Override
    public Info GetInfoData(String account) throws GetUserDataException {
        Info info = accountMapper.GetAccData(account);
        if (info == null){
            throw new GetUserDataException("空");
        }
        return info;
    }

    @Override
    public void ModPassword(String account, String olepassword, String newpassword) throws PasswordNotMatchException{

        String spassword = accountMapper.login(account).getPassword();

        if (spassword.equals(olepassword)){
            accountMapper.ModPassword(account,newpassword);
        }else {
            throw new PasswordNotMatchException("原密码错误");
        }

    }


}
